package com.hpin.fansea.home;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.adapter.GuideClassifyAdapter;
import com.hpin.fansea.bean.GuideListBean;
import com.hpin.fansea.adapter.SpGuideListAdapter;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.GuideClassifyDetail;
import com.hpin.fansea.bean.GuideClassifyResult;
import com.hpin.fansea.bean.GuideList;
import com.hpin.fansea.pulltorefush.PullToRefreshBase;
import com.hpin.fansea.pulltorefush.PullToRefreshListView;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.DensityUtil;
import com.hpin.fansea.utils.HttpUtil;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

/**
 * 办事指南列表页面
 * Created by Aaron on 15/9/9.
 */
public class GuideWorkActivity extends BaseActivity {

    private PullToRefreshListView pListView;

    private List<GuideList> guideLists = null;

    private SpGuideListAdapter spGuideListAdapter = null;
    private int currentPage = 1;// 当前页数

    private ImageView iv_left_all;
    private TextView tv_all;
    private ImageView iv_right_all;
    private RelativeLayout rl_all_classify;

    //办事指南分类的集合
    private List<GuideClassifyDetail> classifyDetailList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_guide);

        initWidget();

        purchase_etClass.setText(getResources().getString(R.string.all_classify));
        currentPage = 0;
        loadDataFromNet(currentClassify);
    }

    private void initWidget() {

        guideLists = new ArrayList<GuideList>();

        iv_left_all = (ImageView) findViewById(R.id.iv_left_all);
        tv_all = (TextView) findViewById(R.id.tv_all);
        iv_right_all = (ImageView) findViewById(R.id.iv_right_all);
        rl_all_classify = (RelativeLayout) findViewById(R.id.rl_all_classify);
        purchase_etClass = (TextView) findViewById(R.id.purchase_etClass);
        ll_current_search = (LinearLayout) findViewById(R.id.ll_current_search);

        pListView = (PullToRefreshListView) findViewById(R.id.list_service_guide);

        spGuideListAdapter = new SpGuideListAdapter(this, guideLists);

        pListView.setAdapter(spGuideListAdapter);

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.guide_work));

        iv_left.setOnClickListener(this);
        rl_all_classify.setOnClickListener(this);

        pListView.setMode(PullToRefreshBase.Mode.BOTH);

        pListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(GuideWorkActivity.this, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                currentPage = 0;
                guideLists.clear();
                loadDataFromNet(currentClassify);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(GuideWorkActivity.this, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                loadDataFromNet(currentClassify);
            }
        });


        pListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(GuideWorkActivity.this, GuideDetailActivity.class);
                Bundle bundle = new Bundle();
                GuideList guideList = guideLists.get(position-1);
                bundle.putSerializable("guideList", guideList);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    /**
     * 网络获取数据
     *
     * @param id 分类的ID
     */
    private void loadDataFromNet(final String id) {

        HttpUtil.getInstance().setGetRequest("加载中...", this,
                Constant.WEB_ROOT + Constant.GUIDELIST + "?token=" + sp.getString(Constant.token, "") + "&communityId="
                        + sp.getString(Constant.communityId, "") + "&pageSize=" + Constant.PAGECOUNT
                        + "&pageIndex=" + (++currentPage) + "&systemType="
                        + Constant.SYSTEM_TYPE + "&gtId=" + id
                , new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {

                        pListView.onRefreshComplete();

                        try {

                            GuideListBean guideListBean = JSONObject.parseObject(str, GuideListBean.class);

                            if (Constant.STATUS_SUCESS.equals(guideListBean.status)) {

                                List<GuideList> lists = guideListBean.result;

                                if (lists!=null && lists.size() ==0 ) {
                                    showToast(Constant.NOMOREDATA);
                                    return;
                                }

                                setListView(lists);

                            }else {
                                showToast(guideListBean.message);
                            }

                        }catch (Exception e) {
                            e.printStackTrace();
                            showToast("获取办事指南失败");
                        }

                    }

                }, new HttpUtil.FailListener() {
                    @Override
                    public void setOnFailListener() {
                        pListView.onRefreshComplete();
                    }
                });

    }

    /**
     * 判断是否有重复并更新
     */
    private void setListView(List<GuideList> tempGuideLists) {
        for (GuideList goods : tempGuideLists) {
            boolean exist = false;
            for (GuideList g : guideLists) {
                if (goods.id_.equals(g.id_)) {
                    exist = true;
                    break;
                }
            }
            if (!exist)
                guideLists.add(goods);
        }

        if (guideLists != null && spGuideListAdapter != null) {
            spGuideListAdapter.setData(guideLists);
            spGuideListAdapter.notifyDataSetChanged();
        }
    }

    private int currentIndex = 0;
    private PopupWindow popupWindow;
    private ListView purchase_categroy_list;
    private GuideClassifyAdapter adapter;
    private TextView purchase_etClass;// 当前搜索的选项
    private LinearLayout ll_current_search;
    private String currentClassify = "";

    /**
     * 获取办事指南分类
     */
    private void getClassifyDataFromNet() {

        RequestParams params = new RequestParams();

        params.addQueryStringParameter("token", sp.getString(Constant.token, ""));
        params.addQueryStringParameter("systemType", Constant.SYSTEM_TYPE);
        params.addQueryStringParameter("pageSize", Constant.PAGECOUNT + "");
        params.addQueryStringParameter("pageIndex", (++currentIndex) + "");
        HttpUtil.getInstance().setGetRequest("获取中...", this, Constant.WEB_ROOT + Constant.GUIDECLASSIFY, params,
                new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            GuideClassifyResult classifyResult = JSONObject.parseObject(str, GuideClassifyResult.class);

                            if (Constant.STATUS_SUCESS.equals(classifyResult.status)) {

                                classifyDetailList = classifyResult.result;
                                //添加一个全部分类
                                GuideClassifyDetail detail = new GuideClassifyDetail();
                                detail.guideTypeName = getResources().getString(R.string.all_classify);
                                detail.id_ = "";
                                classifyDetailList.add(0, detail);

                                //弹出泡泡
                                showPopu(classifyDetailList);

                            } else {
                                showToast(classifyResult.message);
                            }

                        } catch (Exception e) {

                            e.printStackTrace();
                            showToast("获取分类信息失败");

                        }

                    }
                }, null);
    }

    /**
     * 弹出
     *
     * @param list
     */
    private void showPopu(final List<GuideClassifyDetail> list) {
        if (list != null && list.size() > 0) {
            View popwindowView = View.inflate(this, R.layout.popu_classify, null);

            purchase_categroy_list = (ListView) popwindowView.findViewById(R.id.purchase_categroy_list);
            adapter = new GuideClassifyAdapter(this, list);
            purchase_categroy_list.setAdapter(adapter);

            popupWindow = new PopupWindow(popwindowView,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);

            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            popupWindow.update();
            popupWindow.showAsDropDown(ll_current_search, 0, DensityUtil.dip2px(this, 5));

            if (popupWindow != null && popupWindow.isShowing()) {
                iv_left_all.setImageResource(R.mipmap.purchase_class_blue_all);
                tv_all.setTextColor(getResources().getColor(R.color.blue));
                iv_right_all.setImageResource(R.mipmap.purchase_down_arrow_blue);
            }
            // 点击其他地方消失
            popwindowView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                    return false;
                }
            });

            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

                @Override
                public void onDismiss() {
                    iv_left_all.setImageResource(R.mipmap.purchase_class_gray_all);
                    tv_all.setTextColor(getResources().getColor(R.color.gray));
                    iv_right_all.setImageResource(R.mipmap.purchase_down_arrow_gray);

                }
            });

            purchase_categroy_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //TODO
                    currentClassify = list.get(position).id_;

                    purchase_etClass.setText(list.get(position).guideTypeName);

                    //清空集合
                    guideLists.clear();
                    //获取分类的办事指南信息
                    loadDataFromNet(currentClassify);

                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                }
            });
        }
    }


    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.rl_all_classify:


                if (classifyDetailList != null && classifyDetailList.size() > 0 && popupWindow != null) {
                    //TODO
                    popupWindow.showAsDropDown(ll_current_search, 0, DensityUtil.dip2px(this, 5));
                } else {

                    // 获取办事指南分类列表
                    getClassifyDataFromNet();

                }

                break;

            case R.id.iv_left:

                finish();

                break;

            default:
                break;
        }
    }
}
